package com.lyw.h2andjava.controller;

import com.lyw.h2andjava.entity.User;
import com.lyw.h2andjava.service.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController

@RequestMapping(value = "/testh2")
public class TestH2 {
    @Autowired
    private UserRepository userRepository;

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<User> list(){
        List<User> users = userRepository.findAll();
        return users;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public Optional<User> add(@RequestBody User mapper) {

        User result = userRepository.save(mapper);

        Optional<User> user2 = userRepository.findById(result.getId());

        return user2;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public String update(@RequestBody User mapper) {
        try {
            userRepository.saveAndFlush(mapper);
        } catch (Exception e) {
            return new String("failed to update");
        }
        return new String("success to update");
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public String delete( @RequestBody List<String> mapper) {

        int size = mapper.size();
        try {
            if (size != 0) {
                for (String s : mapper) {
                    userRepository.deleteById(s);
                }
            }
        } catch (Exception e) {
            return new String("failed to delete");
        }
        return new String("failed to delete");
    }

}
